package com.tang.thepath;
import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.tang.thepath.db.DefaultDBHelper;
import com.tang.thepath.util.CoordinateUtil;
import com.tang.thepath.util.ScreenBroadcastListener;
import com.tang.thepath.util.ScreenManager;
import com.tang.thepath.util.WakeLockManager;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class MainActivity extends BaseActivity implements View.OnClickListener{
    public static final String TAG = "MainActivity";
    public static final int CHANGE_PASSWORD_REQUEST = 0x0202;
    private boolean serviceStarted = false;
    private View btnVisit;
    private View btnCustomInfo;
    private View btnRepair;
    private View btnProblem;
    private View btnManager;
    private View btnInvoice;

    private TextView tvStatus;
    private DefaultDBHelper dbHelper;
    private Thread uploadLostDataThread;
    private Thread testStartServiceThread;
    private Thread checkLocationServiceThread;
    private boolean registedReceiver = false;
    private TextView tvOfflineNum;
    private Handler handler = new Handler();



    private ScreenManager screenManager = null;
    private boolean isBound  = false;
    private LiveService liveService;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            isBound = true;
            LiveService.LiveBinder binder = (LiveService.LiveBinder) service;
            liveService = binder.getService();
            Log.e("ServiceConnection","onServiceConnected");
        }

        //client 和service连接意外丢失时，会调用该方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("ServiceConnection","onServiceDisconnected");
        }
    };

    //高德地图定位服务
    private AMapLocationClient mlocationClient;
    private int locationInterval  = 1000 * 60;
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");






    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cel_visit:
                startActivity(new Intent(getContext(), VisitListActivity.class));
                break;
            case R.id.cel_custom_info:
                startActivity(new Intent(getContext(),CustomListActivity.class));
                break;
            case R.id.tv_status:
                toast("请点击右上角菜单操作");
                break;
            case R.id.cel_manager:
                startActivity(new Intent(getContext(),UserListActivity.class));
                break;
            case R.id.cel_repair:
                startActivity(new Intent(getContext(),RepairListActivity.class));
                break;
            case R.id.cel_problem:
                startActivity(new Intent(getContext(),ProblemListActivity.class));
                break;
            case R.id.cel_invoice:
                startActivity(new Intent(getContext(),InvoiceActivity.class));
                break;

        }
    }

    //读取遗留的数据
    protected class ReadLostData implements Runnable{

        @Override
        public void run() {
            final List<Map> list = dbHelper.queryListMap("select * from locations",null);

            for (int i=0;i<list.size();i++){
                Map item = list.get(i);
                long insertId =  Long.parseLong(item.get("id").toString());
                int outsignId = Integer.parseInt(item.get("outsign_id").toString());
                double lat = Double.parseDouble(item.get("lat").toString());
                double lng = Double.parseDouble(item.get("lng").toString());
                long recordTime = Long.parseLong(item.get("record_time").toString());
                doUploadLocation(insertId,outsignId,lat,lng,recordTime);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    protected synchronized void startReal(){
        serviceStarted = true;
        Const.REAL_UPLOADING = true;
        mlocationClient.startLocation();
    }

    protected synchronized void stopReal(){
        serviceStarted = false;
        Const.REAL_UPLOADING = false;
        mlocationClient.stopLocation();
    }

    protected void logout(){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setMessage("确定退出吗?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        stopReal();
                        MainActivity.this.finish();
                        startActivity(new Intent(MainActivity.this,LoginActivity.class));
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        // 显示
        normalDialog.show();

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if(itemId == R.id.menu_logout){
            logout();
        }else if(itemId == R.id.menu_password){
            startActivityForResult(new Intent(this,PasswordActivity.class),CHANGE_PASSWORD_REQUEST);
        }
        return true;
    }


    protected Runnable testStartService = new Runnable() {
        @Override
        public void run() {
            while(true){
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int minute = cal.get(Calendar.MINUTE);
                int nowSecond = (hour * 3600) + (minute * 60);
                int startSecond = 27000; // (7*3600) + (30*60)
                int endSecond = 70140; // (19*3600) + (29*60)

                if(nowSecond >= startSecond && nowSecond <= endSecond){//7点30到19点30

                    if(!serviceStarted){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                startReal();
                            }
                        });
                    }
                }else{

                    if(serviceStarted){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                stopReal();
                            }
                        });
                    }
                }

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION}, 0x01);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setHomeButtonEnabled(false);
            actionBar.setDisplayHomeAsUpEnabled(false);
        }


        btnVisit = findViewById(R.id.cel_visit);
        btnCustomInfo = findViewById(R.id.cel_custom_info);
        btnRepair = findViewById(R.id.cel_repair);
        btnProblem = findViewById(R.id.cel_problem);
        btnManager = findViewById(R.id.cel_manager);
        btnInvoice = findViewById(R.id.cel_invoice);

        tvStatus = (TextView) findViewById(R.id.tv_status);
        tvOfflineNum= (TextView) findViewById(R.id.tv_offline_num);

        btnVisit.setOnClickListener(this);
        btnCustomInfo.setOnClickListener(this);
        tvStatus.setOnClickListener(this);
        btnRepair.setOnClickListener(this);
        btnProblem.setOnClickListener(this);
        btnManager.setOnClickListener(this);
        btnInvoice.setOnClickListener(this);


        dbHelper = DefaultDBHelper.getInstance(getApplicationContext());

        if(Const.NETWORK_MOD > 0){
            startDatabaseThread();
        }

        //保活方案1(提高进程优先级)
        bindService(new Intent(this,LiveService.class),conn,BIND_AUTO_CREATE);
        //保活方案2(提高进程优先级)
        screenManager  = ScreenManager.getInstance(this);
        ScreenBroadcastListener listener = new ScreenBroadcastListener(this);
        listener.registerListener(new ScreenBroadcastListener.ScreenStateListener() {
            @Override
            public void onScreenOn() {
                screenManager.finishActivity();
                WakeLockManager wakeLockManager = WakeLockManager.getInstance();
                wakeLockManager.release();
                moveTaskToBack(true);
            }

            @Override
            public void onScreenOff() {
                WakeLockManager wakeLockManager = WakeLockManager.getInstance();
                wakeLockManager.acquire(getApplicationContext());
                screenManager.startActivity();

            }
        });

        //配置高德定位
        mlocationClient = new AMapLocationClient(getApplicationContext());
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Sport);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setLocationCacheEnable(true);
        mLocationOption.setInterval(locationInterval);
        //mLocationOption.setMockEnable(false);
        mlocationClient.setLocationOption(mLocationOption);
        mlocationClient.setLocationListener(locationListener);

        //开启检测离线数据线程
        startOfflineNumThread();

        //开启自动上报服务
        testStartServiceThread = new Thread(testStartService);
        testStartServiceThread.start();
    }

    protected void startOfflineNumThread(){

        final Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Map item = dbHelper.queryItemMap("select count(*) as c from locations",null);
                tvOfflineNum.setText(item.get("c").toString());
            }
        };

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        handler.post(runnable);
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private AMapLocationListener locationListener =  new AMapLocationListener(){

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    double lat = aMapLocation.getLatitude();
                    double lng = aMapLocation.getLongitude();

                    //可在其中解析amapLocation获取相应内容。
                    Date date = new Date(aMapLocation.getTime());
                    String locationDate = df.format(date);//定位时间
                    String msg = locationDate+"  lng:"+lng+"  lat:"+lat+"  type:"+aMapLocation.getLocationType();
                    Log.e("Amap",msg);

                    String type = "";
                    if(aMapLocation.getLocationType() == 1){
                        type = "GPS";
                        //转换坐标
                        double latlng[] = CoordinateUtil.transformFromWGSToGCJ(aMapLocation);
                        lat=latlng[0];
                        lng=latlng[1];
                    }else if(aMapLocation.getLocationType() == 2){
                        //type = "两次";
                        return;
                    }else if(aMapLocation.getLocationType() == 4){
                        //type = "缓存";
                        return;
                    }else if(aMapLocation.getLocationType() == 5){
                        type = "wifi";
                    }else if(aMapLocation.getLocationType() == 6){
                        type = "基站";
                    }
                    int outsignId = 0;
                    long recordTime = System.currentTimeMillis() / 1000;

                    //插入数据库
                    long id = dbHelper.insert("locations",new String[]{"outsign_id","lat","lng","record_time"},new Object[]{outsignId,String.valueOf(lat),String.valueOf(lng),recordTime});
                    doUploadLocation(id,outsignId,lat,lng,recordTime);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };


    protected void startDatabaseThread(){
        uploadLostDataThread = new Thread(new ReadLostData());
        uploadLostDataThread.start();
    }

    protected synchronized void doUploadLocation(final long insertId, final int outsignId, final double lat, final double lng, final long record_time){
        if(Const.NETWORK_MOD == 0){
            return;
        }
        Intent intent = new Intent(getContext(), PositionIntentService.class);
        intent.putExtra("outsign_id", outsignId);
        intent.putExtra("lat",lat);
        intent.putExtra("lng",lng);
        intent.putExtra("record_time",record_time);
        intent.putExtra("insert_id",insertId);
        startService(intent);
    }




    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG,"onResume");
        /*if(serviceStarted){
            registerBroadcast();
        }*/
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG,"onStop");
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        Log.e(TAG,"onDestroy");
        //停止地址服务
        stopReal();
        //销毁高德地图组件
        mlocationClient.onDestroy();
        //释放CPU锁
        WakeLockManager wakeLockManager = WakeLockManager.getInstance();
        wakeLockManager.release();
        //解绑LiveService
        unbindService(conn);
        super.onDestroy();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == CHANGE_PASSWORD_REQUEST && resultCode == RESULT_OK){
            SharedPreferences sp = getSharedPreferences("login",MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.remove("password");
            editor.apply();
            finish();
            startActivity(new Intent(this,LoginActivity.class));

        }
    }
}
